<template>
  <div>
    <el-form :model="form" inline>
      <el-form-item label="班级名称"
        ><el-input v-model="form.name" placeholder="请输入班级名称"></el-input
      ></el-form-item>
      <el-button type="primary" @click="search">查 询</el-button>
      <el-button type="primary" @click="add">添 加</el-button>
    </el-form>
    <el-table :data="tableData">
      <el-table-column label="班级名" prop="name" />
      <el-table-column label="类型" prop="type">
        <template slot-scope="scope">
          <span v-for="item in types" :key="item.id">
            <span v-if="scope.row.type === item.id">
              {{ item.type }}
            </span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="班主任" prop="teacherName" />
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button @click="deleteHandler(scope.row)" size="mini" type="text"
            >删除</el-button
          >
          <el-button @click="detailHandler(scope.row)" size="mini" type="text"
            >编辑</el-button
          >
          <el-button @click="checkHandler(scope.row)" size="mini" type="text"
            >详情</el-button
          >
          <el-button
            v-show="scope.row.type == 0"
            @click="statistic(scope.row)"
            size="mini"
            type="text"
            >统计</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="prev, pager, next"
      :total="total"
      :current-page="currentPage"
      @current-change="handleCurrentChange"
    />
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible">
      <el-form
        :model="tableForm"
        ref="tableForm"
        :rules="tableRules"
        label-width="100px"
        label-position="left"
      >
        <el-form-item label="班级类型" prop="type">
          <el-select
            v-model="tableForm.type"
            placeholder="请选择班级类型"
            :disabled="disabled"
          >
            <el-option
              v-for="item in types"
              :key="item.id"
              :label="item.type"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="执照类型"
          prop="license"
          v-if="tableForm.type == 0"
        >
          <el-select
            v-model="tableForm.license"
            placeholder="请选择执照类型"
            :disabled="disabled"
            multiple
          >
            <el-option
              v-for="item in licenses"
              :key="item.id"
              :label="item.value"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="年份" prop="year">
          <el-input-number v-model="tableForm.year" :disabled="disabled" />
        </el-form-item>
        <el-form-item label="期数" prop="grade">
          <el-input-number
            :min="1"
            v-model="tableForm.grade"
            :disabled="disabled"
          />
        </el-form-item>
        <el-form-item label="学员录入" prop="students">
          <el-select
            placeholder="请选择学员名单"
            v-model="tableForm.students"
            :disabled="disabled"
            multiple
            filterable
          >
            <el-option
              v-for="item in students"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="班主任"
          prop="teacher"
          v-if="tableForm.license.length <= 1 && tableForm.type == 0"
        >
          <el-select
            placeholder="请选择班主任"
            v-model="tableForm.teacher"
            :disabled="disabled"
            filterable
          >
            <el-option
              v-for="item in teachers"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div v-if="!disabled" slot="footer" class="dialog-footer">
        <el-button @click="resetHandler('tableForm')">重 置</el-button>
        <el-button type="primary" @click="submit('tableForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具 js，第三方插件 js，json 文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import { getStudents, getTeachers, getByGradeId } from "@/api/user";
import gradeApi from "@/api/grade/index";
import subjectApi from "@/api/subject/index";

let gradeId;
const currentYear = new Date().getFullYear();
export default {
  //import 引入的组件需要注入到对象中才能使用
  components: {},
  props: {},
  data() {
    const validateType = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("班级类型不得为空！"));
      } else {
        callback();
      }
    };
    const validateLicense = (rule, value, callback) => {
      if (this.tableForm.type == 0 && value.length == 0) {
        callback(new Error("执照类型不得为空!"));
      } else {
        callback();
      }
    };
    const validateYear = (rule, value, callback) => {
      if (value < currentYear) {
        callback(new Error("年份不能比当前年份小！"));
      } else {
        callback();
      }
    };
    //这里存放数据
    return {
      dialogTitle: "添加班级", //对话框的title
      editOrAdd: false, //表示是更新还是添加，如果是false表示是添加，如果true表示是更新
      setLicense: false, //显示选择是TA还是PA的执照类型
      form: { name: "" },
      dialogFormVisible: false,
      tableForm: {
        type: "",
        year: 2024,
        grade: 1,
        license: [],
        students: [],
        teacher: "",
      },
      tableRules: {
        type: [{ require: true, trigger: "blur", validator: validateType }],
        license: [
          { require: true, trigger: "blur", validator: validateLicense },
        ],
        year: [
          {
            require: true,
            trigger: "blur",
            validator: validateYear,
          },
        ],
      },
      disabled: false,
      types: [
        { id: 0, type: "基础执照班" },
        { id: 1, type: "机型班" },
      ],
      licenses: [
        { id: 0, value: "TA" },
        { id: 1, value: "PA" },
      ],
      students: [],
      teachers: [],
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      subjects: [],
    };
  },
  //计算属性 类似于 data 概念
  computed: {},
  //监控 data 中的数据变化
  watch: {},
  //方法集合
  methods: {
    //统计班级信息
    statistic(params) {
      if (params.type == 0) {
        gradeId = params.id;

        this.$router.push({
          path: "/user/statistcs",
          query: { gradeId, name: params.name },
        });
      } else {
        this.$message({
          message: "只有基础执照培训支持统计数据！",
          type: "error",
        });
      }
    },
    setTableForm(params) {
      const name = params.name;
      this.tableForm.license = [];
      if (params.type == 0) {
        // const str = name.substring(name.indexOf("期") + 1, name.indexOf("班"));
        // this.tableForm.license = str === "PA" ? 1 : 0;
        //如果是基础执照班，看是PA+TA这种合班的形式还是只有PA和只有TA这种单独的形式
        if (name.indexOf("+") > -1) {
          this.tableForm.license.push(1);
          this.tableForm.license.push(0);
        } else {
          const str = name.substring(
            name.indexOf("期") + 1,
            name.indexOf("班")
          );
          if (str === "PA") {
            this.tableForm.license.push(1);
          } else {
            this.tableForm.license.push(0);
          }
        }
      }
      this.tableForm.grade = name.substring(
        name.indexOf("年") + 2,
        name.indexOf("期")
      );
      this.tableForm.id = params.id;
      this.tableForm.year = name.substring(0, 4);
      this.tableForm.type = params.type;
      this.tableForm.teacher = params.teacherId;
      this.dialogFormVisible = true;

      //查询该课程的学员信息
      getStudents().then((response) => {
        this.students = response.data;
        getByGradeId(params.id).then((res) => {
          this.tableForm.students = res.data;
        });
      });
    },
    checkHandler(params) {
      this.disabled = true;
      this.dialogTitle = "查看班级";
      this.setTableForm(params);
    },
    detailHandler(params) {
      this.editOrAdd = true;
      this.disabled = false;
      this.dialogTitle = "更新班级";
      this.setTableForm(params);
    },
    deleteHandler(params) {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          gradeApi.delete(params.id).then((res) => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.list(1);
            this.getTotal();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      this.list(currentPage);
    },
    add() {
      this.dialogTitle = "添加班级";
      this.editOrAdd = false;
      this.dialogFormVisible = true;
      getStudents().then((res) => {
        this.students = res.data;
        this.tableForm = {
          type: "",
          year: 2024,
          grade: 1,
          license: [],
          students: [],
          teacher: "",
        };
      });
    },
    search() {
      this.list(1);
      this.getTotal();
    },
    submit(tableForm) {
      this.$refs[tableForm].validate((valid) => {
        if (valid) {
          if (!this.editOrAdd) {
            console.log(this.tableForm);

            gradeApi.add(this.tableForm).then((result) => {
              this.$message({
                message: `${result.message}`,
                type: "success",
              });
              this.dialogFormVisible = false;
              this.getTotal();
              this.list(1);
            });
          } else {
            gradeApi.update(this.tableForm).then((result) => {
              this.$message({
                message: `${result.message}`,
                type: "success",
              });
              this.dialogFormVisible = false;
              this.getTotal();
              this.list(1);
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetHandler(tableForm) {
      this.$refs[tableForm].resetFields();
    },
    list: async function (currentPage) {
      const res = await gradeApi.list(
        this.form.name,
        currentPage,
        this.pageSize
      );
      this.tableData = res.data;
    },
    getTotal: async function () {
      const res = await gradeApi.total(this.form.name);
      this.total = res.data;
    },
    getSubjects(params) {
      subjectApi.getAll().then((res) => {
        if (params == "PA") {
          this.subjects = res.data.filter(
            (i) => i.name != "R3M5航空涡轮发动机"
          );
        } else if (params == "TA") {
          this.subjects = res.data.filter(
            (i) => i.name != "R3M6航空活塞发动机"
          );
        }
      });
    },
  },
  //生命周期 - 创建完成（可以访问当前 this 实例）
  created() {
    this.tableForm.year = currentYear;
    // getStudents().then((res) => {
    //   this.students = res.data;
    // });
    getTeachers().then((response) => {
      this.teachers = response.data;
    });
    this.list(1);
    this.getTotal();
  },
  //生命周期 - 挂载完成（可以访问 DOM 元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有 keep-alive 缓存功能，这个函数会触发
};
</script>
<style scoped></style>
